using System.Collections.Generic;

namespace DrawToolsLib {
    /// <summary>
    /// Delete command.
    /// Applied to list selection.
    /// </summary>
    class CommandDelete : CommandBase {
        private Dictionary<int, GraphicsBase> delList;    // contains selected items which are deleted

        /// <summary>
        /// Create this command BEFORE applying Delete function.
        /// </summary>
        public CommandDelete(DrawingCanvas d) {
            delList = new Dictionary<int, GraphicsBase>();

            // Make clone of the list selection.
            foreach (GraphicsBase g in d.Selection) {
                delList.Add(d.GraphicsList.IndexOf(g), g);
            }
        }

        /// <summary>
        /// Restore deleted objects
        /// </summary>
        public override void Undo(DrawingCanvas d) {

            // Insert all objects from cloneList to GraphicsList
            foreach (KeyValuePair<int, GraphicsBase> g in delList) {
                if ((g.Key >= 0) && (g.Key <= d.GraphicsList.Count)) {  // "<=" is correct !
                    d.Push(g.Key, g.Value);
                } else {
                    // Bug: we should not be here.Add to the end anyway.
                    d.Push(g.Value);

                    System.Diagnostics.Trace.WriteLine("CommandDelete.Undo - incorrect index");
                }
            }

            foreach (GraphicsBase g in d.GraphicsList) {
                g.IsSelected = (delList.ContainsValue(g)) ? true : false;
            }
        }

        /// <summary>
        /// Delete objects again.
        /// </summary>
        public override void Redo(DrawingCanvas drawingCanvas) {
            // Delete from list all objects kept in cloneList.
            // Use object IDs for deleting, don't beleive to objects order.

            foreach (KeyValuePair<int, GraphicsBase> g in delList) {
                drawingCanvas.Pop(g.Key);
            }
        }
    }
}
